﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NetFrame.EnDecode {
    public class EnDecodeFun {

        /// <summary>
        /// 消息长度编码
        /// </summary>
        /// <param name="cache"></param>
        /// <returns></returns>
        public static byte[] LengthEncoding(byte[] cache) {
            if (cache == null || cache.Length <= 0) { return null; }

            ByteArray ba = new ByteArray();
            ba.Write(cache.Length);
            ba.Write(cache);
            byte[] result = ba.GetBuffer();
            ba.Close();

            return result;

        }

        /// <summary>
        /// 消息长度解码
        /// </summary>
        /// <param name="cache"></param>
        /// <returns></returns>
        public static byte[] LengthDecoding(ref List<byte> cache) {
            if (cache == null || cache.Count < 4) { return null; }
            else {
                

                ByteArray ba = new ByteArray(cache.ToArray());
                int len = ba.ReadInt32();

                //如果长度不够，返回
                if (cache.Count - 4 < len) {

                    ba.Close();

                    return null;

                }
                else {
                    byte[] value = new byte[len];
                    Buffer.BlockCopy(cache.ToArray(), 4, value, 0, value.Length);

                    cache.RemoveRange(0, 4 + len);
                    ba.Close();

                    return value;

                }
            }

        }
    }
}
